<?php

namespace app\index\controller;

use app\common\controller\Log;
use app\common\model\Levels;
use app\common\model\Member;
use app\common\model\MemberFinance;
use app\common\model\Recharge;
use app\common\model\Withdrawal;
use think\Db;
use think\Validate;
use app\common\api\controller\Bonus;

class TradingHall extends Home
{
    protected $beforeActionList = [
        'check_load'
    ];

    /**
     * 初始化
     */
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 提现申请
     */
    public function wdReply()
    {
        if (!request()->isPost()) {
            $this->apiError('非法操作！');
        }
        $uid = $this->uid;
        $userinfo = Member::get($uid);

        $rule = get_bonus_rule();//交易规则

        $nowday = date('w');
        $allowday = explode(',', get_bonus_rule('wd_time'));
        if (!in_array($nowday, $allowday)) {
            $this->apiError('今日不可提现！');
        }
        $wdinfo = Db::name('withdrawal')->where(['userid' => $uid, 'status' => 0])->find();
        if (!empty($wdinfo)) {
            $this->apiError('已申请过提现，等申请批准后方可再次申请!');
        }
        $today = strtotime('today');
        $map['userid'] = $uid;
        $moneytype = input('moneytype', 2);
        $map['handtime'] = ['egt', $today];
        $count = Db('withdrawal')->where($map)->count();
        if ($count >= 5) {
            $this->apiError('一天最多只能提现五次！');
        }
        $data = input('post.');
        $validate = Validate('withdrawal');
        if (!$validate->check($data)) {
            $this->apiError($validate->getError());
        }
        if (!$data['password']) {
            $this->apiError('请输入提现密码');
        }
        if ($data['password'] != $userinfo['psd2']) {
            $this->apiError('提现密码输入错误');
        }
        unset($data['password']);

//            if ($data['phone'] != session('phone_verify_code')) {
//                $this->error('手机验证码错误');
//            }
//            unset($data['phone']);
//            session('phone_verify_code', null);

        $money = $data['money'];
        $data['userid'] = $uid;
        $data['usernumber'] = $userinfo['usernumber'];

        $financeObj = MemberFinance::where('uid', $uid)->find();
        if ($moneytype == 2) {
            $field = 'hasmoney';
            $fee = $money * $rule['fee_wd'] * 0.01;
        } else {
            $field = 'hasgreen';
            $fee = 0;
        }
        if ($financeObj->$field < $money) {
            $this->apiError('提现金额大于账户余额');
        }

        if ($rule['min_wd'] > $money) {
            $this->apiError('提现金额小于起提额度');
        }

        if ($money % $rule['multiple_wd']) {
            $this->apiError("提现金额必须是{$rule['multiple_wd']}的整数倍");
        }

        $data['fee'] = $fee;
        $data['createtime'] = time();
        $data['status'] = 0;
        $data['money'] = $money - $fee;

        if ($moneytype == 3) {
            $total1 = get_bonus_rule('total1');
            $total2 = get_bonus_rule('total2');
            $price = round($total1 / $total2, 2);

            $message = ($price * $money);
            $data['message'] = '实际金额为 ' . $message . '元';
        }

        unset($data['token']);
        Db::startTrans();
        try {

            Db('withdrawal')->insert($data);

            $financeObj->$field -= $money;
            $financeObj->save();

            $type_arr = array('recordtype' => 0, 'moneytype' => $moneytype, 'changetype' => 22);
            $money_arr = array('money' => $money, 'hasmoney' => $financeObj->$field);
            money_change($type_arr, $uid, get_com(), $money_arr);

            // 提交事务
            Db::commit();
            $this->apiSuccess('提现申请成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->apiError('申请失败');
        }
    }

    /**
     * 根据银行卡得到银行名称
     */
    public
    function getBankName()
    {
        if (request()->isPost()) {
            $banknumber = input('banknumbe');
            $str = substr($banknumber, 0, 6);
            $lists = config('BANKLIST');
            $bankname = $lists[$str];
            if ($bankname) {
                $this->success($bankname);
            } else {
                $this->error('该卡号错误！');
            }

        } else {
            $this->error('非法操作！');
        }
    }

    /**
     * 提现记录
     */
    public
    function wdRecord()
    {
        $uid = is_login();
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $maps['userid'] = $map['userid'] = $uid;

        $list = Db('withdrawal')->where($map)->order('createtime desc')->paginate(20, false, ['query' => $maps]);
        $page = $list->render();
        if (request()->isMobile()) {
            $list = Db('withdrawal')->where($map)->order('createtime desc')->select();
        }
        $this->assign('_list', $list);
        $this->assign('page', $page);

        $this->searchCondition($maps);

        $this->assign('title', '提现');
        return $this->fetch('wdrecord');
    }

    /**
     * 转币（不同币种转换）
     */
    public function tfReply1()
    {
        $uid = $this->uid;
        $bonusRole = get_bonus_rule();//交易规则
        $financeObj = MemberFinance::where('uid', $uid)->find();
//        if ($userinfo['isbill'] < 1) {
//            $this->apiError('权限不足！');
//        }
        if (request()->isPost()) {
            $money = input('money', 0);                                  //转入用户
            $tftype = input('type', 1);

            if ($tftype == 1) {//报单币转报单币
                $outfiled = 'hasmoney';
                $infiled = 'hasbill';
                $outmoneytype = 2;
                $inmoneytype = 1;
            } elseif ($tftype == 2) {//报单币转报单币
                $outfiled = 'hasmoney';
                $infiled = 'hascp';
                $outmoneytype = 2;
                $inmoneytype = 3;
            }

            if ($financeObj->$outfiled < $money) {
                $this->apiError('转币金额大于账户余额');
            }

            if ($bonusRole['min_tf'] > $money) {
                $this->apiError('转币金额小于最小转币金额');
            }

//            if ($money % $multipleWd) {
//                $this->apiError("转币金额必须是{$multipleWd}的整数倍");
//            }

            $sql1 = "update zx_member_finance  set {$outfiled} = {$outfiled}-{$money} where uid={$uid}";
            switch ($inmoneytype) {
                case 1:
                    $sql2 = "update zx_member_finance  set {$infiled} = {$infiled}+{$money},allbill = allbill + {$money} where uid={$uid}";
                    break;
                case 3:
                    $sql2 = "update zx_member_finance  set {$infiled} = {$infiled}+{$money},allcp = allcp + {$money} where uid={$uid}";
                    break;
            }

            $res1 = Db::execute($sql1);
            $res2 = Db::execute($sql2);

            if ($res1 && $res2) {
                $type_arr = array('recordtype' => 0, 'moneytype' => $outmoneytype, 'changetype' => 33);
                $money_arr = array('money' => $money, 'hasmoney' => $financeObj->$outfiled - $money);
                money_change($type_arr, $uid, $uid, $money_arr);

                $type_arr = array('recordtype' => 1, 'moneytype' => $inmoneytype, 'changetype' => 33);
                $money_arr = array('money' => $money, 'hasmoney' => $financeObj->$infiled + $money);
                money_change($type_arr, $uid, $uid, $money_arr);

                $this->apiSuccess('转币成功', url('financialflow'));
            } else {
                $this->apiError('交易失败');
            }
        }
    }

    /**
     * 会员间转币
     * @return mixed
     */
    public function tfReply2()
    {
        $uid = $this->uid;
        $bonusRole = get_bonus_rule();//交易规则
        $userinfo = Db('member')->where('uid', $uid)->find();

        if (request()->isPost()) {
            $money = input('money', 0);                                  //转入用户
            if ($money <= 0) {
                $this->apiError('转币额度必须大于0！');
            }
            $tftype = input('type', 1);
            $tusernumber = input('tousernumber');
            if (!$tusernumber) {
                $this->apiError('请输入对方账号/手机号码！');
            }
            $password = trim(input('password'));
            if ($password != $userinfo['psd2']) {
                $this->apiError('支付密码错误！');
            }
            $tuser = Db('member')->where('usernumber', $tusernumber)->whereOr('mobile', $tusernumber)->find();

            if (!$tuser) {
                $this->apiError('对方账户不存在！');
            }

            if ($uid == $tuser['uid']) {
                $this->apiError('不能自己转给自己！');
            }

//            $tuijianidsArr = explode(',', trim($userinfo['tuijianids'], ','));
//            $ttuijianidsArr = explode(',', trim($tuser['tuijianids'], ','));
//
//            if (!in_array($tuser['uid'], $tuijianidsArr) && !in_array($uid, $ttuijianidsArr)) {
//                $this->apiError('只能转给团队内成员！');
//            }

            switch ($tftype) {
                case 1:
                    $hasfiled = 'hasbill';
                    $allfiled = 'allbill';
                    $moneytype = 1;
                    break;
                case 2:
                    $hasfiled = 'hasmoney';
                    $allfiled = 'allmoney';
                    $moneytype = 2;
                    break;
                case 3:
                    $hasfiled = 'hascp';
                    $allfiled = 'allcp';
                    $moneytype = 3;
                    break;
                default:
                    $this->apiError('非法操作！');
                    break;

            }

            $financeObj = MemberFinance::where('uid', $uid)->find();
            if ($financeObj->$hasfiled < $money) {
                $this->apiError('转币金额大于账户余额');
            }

            if ($bonusRole['min_tf'] > $money) {
                $this->apiError('转币金额小于最小转币金额');
            }

            if ($bonusRole['multiple_tf'] > 0) {
                if ($money % $bonusRole['multiple_tf']) {
                    $this->apiError("转币金额必须是{$bonusRole['multiple_tf']}的整数倍");
                }
            }

            $sql1 = "update zx_member_finance  set {$hasfiled} = {$hasfiled}-{$money} where uid={$uid}";
            $sql2 = "update zx_member_finance  set {$hasfiled} = {$hasfiled}+{$money},$allfiled = $allfiled + {$money} where uid={$tuser['uid']}";

            $res1 = Db::execute($sql1);
            $res2 = Db::execute($sql2);

            if ($res1 && $res2) {
                $type_arr = array('recordtype' => 0, 'moneytype' => $moneytype, 'changetype' => 34);
                $money_arr = array('money' => $money, 'hasmoney' => $financeObj->$hasfiled);
                money_change($type_arr, $uid, $tuser['uid'], $money_arr);

                $tfinanceObj = MemberFinance::where('uid', $tuser['uid'])->find();
                $type_arr = array('recordtype' => 1, 'moneytype' => $moneytype, 'changetype' => 34);
                $money_arr = array('money' => $money, 'hasmoney' => $tfinanceObj->$hasfiled);
                money_change($type_arr, $tuser['uid'], $uid, $money_arr);

                $this->apiSuccess('转币成功', url('tfRecord'));
            } else {
                $this->apiError('交易失败');
            }
        }
    }

    /**
     * 充值申请
     */
    public
    function reReply()
    {
        $uid = $this->uid;
        $uinfo = Db('member')->find($uid);

        if (!request()->isPost()) {
            $this->apiError('非法操作！');
        }
        $data = input();
        $rule = [
            'money|充值金额' => 'require',
            'icon|打款截图' => 'require'
        ];
        $validata = new Validate($rule);
        if (!$validata->check($data)) {
            $this->apiError($validata->getError());
        }

        $rdata = [
            'userid' => $uid,
            'hasmoney' => $uinfo['hasmoney'],
            'money' => $data['money'],
            'mobile' => $data['mobile'],
            'moneytype' => $data['moneytype'],
            'icon' => $data['icon'],
        ];

        $res = Recharge::create($rdata);
        if ($res->id) {
            $this->apiSuccess('充值申请成功');
        } else {
            $this->apiError('充值申请失败');
        }
    }

    /**
     * 充值记录
     */
    public
    function reRecord()
    {
        $uid = is_login();
        $where = $this->getMap('createtime');
        $map = $where['map'];
        $maps = $where['maps'];
        $status = input('status', -2);

        if ($status > -2) {
            $maps['status'] = $map['status'] = $status;
        }

        $maps['userid'] = $map['userid'] = $uid;

        $list = Db('Recharge')->where($map)->order('createtime desc')->paginate(20, false, ['query' => $maps]);
        $page = $list->render();
        if (request()->isMobile()) {
            $list = Db('Recharge')->where($map)->order('createtime desc')->select();
        }
        $this->assign('_list', $list);
        $this->assign('page', $page);
        /*追加查询条件*/
        $arr = [
            [
                'type' => 'select',
                'name' => 'status',
                'inputid' => '',
                'readonly' => '',
                'title' => '状态',
                'option' => [
                    -2 => '全部',
                    -1 => '拒批',
                    0 => '尚未审核',
                    1 => '同意'
                ],
                'value' => $status,
            ]
        ];
        $this->searchCondition($maps, $arr);
        $this->assign('title', "充值");
        return $this->fetch('rerecord');
    }


    public
    function reRecord1()
    {
        $uid = is_login();

        $map['moneytype'] = 3;
        $map['userid'] = $uid;
        $list = Db('Recharge')->where($map)->order('createtime desc')->select();
        $this->assign('_list', $list);
        $this->assign('title', "充值");
        return $this->fetch();
    }

    /**
     * 申请成为报单中心
     */
//    public function billReplay(){
//    	$uid = is_login();
//    	$info = self::$Member->where(array('uid'=>$uid))->field('isbill')->find();
//    	if(IS_POST){
//
//    	}else{
//			$this->assign('info',$info);
//    		$this->title="升级申请";
//    		$this->display();
//    	}
//    }

    /**
     * 财务流水
     */
    public function financialFlow()
    {
        $page = input('page');
        $start = ($page - 1) * self::$totalList;
        $uid = $this->uid;

        $moneytype = input('moneytype');
        $changetype = input('changetype');
        $recordtype = input('recordtype', -1);
        $remark = input('remark');
        $map = [
            'targetuserid' => $uid
        ];

        if ($moneytype > -1) {
            $map['moneytype'] = $moneytype;
        }

        if ($changetype > -1) {
            $map['changetype'] = $changetype;
        }

        if ($recordtype > -1) {
            $map['recordtype'] = $recordtype;
        }

        $totalCount = Db('money_change')
            ->where($map)
            ->count();

        $list = Db('money_change')
            ->where($map)
            ->order('createtime desc,id desc')
            ->limit($start, self::$totalList)
            ->select();

        if ($totalCount > 0) {
            $changetypes = config('changetype');
            $moneytypes = config('moneytype');
            foreach ($list as &$val) {
                $val['createtime'] = date('Y-m-d H:i:s', $val['createtime']);
                $val['changetype'] = $changetypes[$val['changetype']];
                $val['moneytype'] = $moneytypes['title'][$val['moneytype']];
                $val['money'] = number_format($val['money'], 2);
                $val['usernumber'] = $val['userid'] == 0 ? '公司' : Member::where('uid', $val['userid'])->value('usernumber');
            }
        }

        $this->apiSuccess('财务流水', ['data' => $list, 'totalCount' => $totalCount]);
    }

    /**
     * 资金管理
     */
    public
    function finance()
    {
        $uid = is_login();
        $user = Db('member')->where('uid', $uid)->find();
        /*累计收入*/
        $bonusTotal = Db('bonus_total')->where('userid', $uid)->find();

        $this->assign('user', $user);
        $this->assign('bonusTotal', $bonusTotal);
        $this->assign('title', '累计收益');
        return $this->fetch();
    }
}